package cn.itcast.bos.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.domain.system.Menu;
import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.repository.MenuRepository;
import cn.itcast.bos.repository.PermissionRepository;
import cn.itcast.bos.repository.RoleRepository;
import cn.itcast.bos.service.RoleService;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleRepository roleRepository;
	
	@Autowired
	private PermissionRepository permissionRepository;
	
	@Autowired
	private MenuRepository menuRepository;

	@Override
	public List<Role> findAllRoles(User user) {
		if(user != null && user.getUsername().equals("admin")) {
			return roleRepository.findAll();
		}
		return roleRepository.findByUser(user.getId());
	}

	@Override
	public List<Role> findAll() {
		return roleRepository.findAll();
	}

	@Override
	public void save(Role role, String[] permissionIds, String menuIds) {
		//保存角色
		roleRepository.save(role);
		//角色关联权限
		if(permissionIds !=null && permissionIds.length >0) {
			for (String permissionId : permissionIds) {
				//查询权限
				Permission permission = permissionRepository.findOne(Integer.parseInt(permissionId));
				role.getPermissions().add(permission);
			}
		}
		
		//角色关联菜单
		if(StringUtils.isNotBlank(menuIds)) {
			String[] menuIdArr = menuIds.split(",");
			for (String meduId : menuIdArr) {
				//查询菜单
				Menu menu = menuRepository.findOne(Integer.parseInt(meduId));
				role.getMenus().add(menu);
			}
		}
		
	}

}
